Imports Visio
Imports System.IO
Imports System.Xml
Imports System.Data
Imports System.Web.UI.DataSourceSelectArguments
Imports My

Imports System.Configuration.ConfigurationManager

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected ShapesNode As New Specialized.HybridDictionary

    Private moNode As TreeNode


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            'Dim s$ = System.Configuration.ConfigurationManager.AppSettings("DefaultVSDFileName")
            'First time only
            If Not Page.IsPostBack Then

                'Using Viewstate to hold environment vars between postbacks
                'Get the default values for Env Vars from web.config
                For Each sKey As String In AppSettings.AllKeys
                    ViewState.Add(sKey, AppSettings(sKey))
                Next
                'Set the user id

                GetUserId()

                'Using Viewstate env var to locate batch files
                'and list for user to select      
                GetVSDFilesList(ddlVSDFilesList)
                GetBatchFilesList(ddlFilesList)

                GetSkippedFilesList(cblSkipped)

                'ddlFilesList_SelectedIndexChanged(sender, e)

                RebuildTreeview()

            Else

                If lblErrorMessage.Text.Length Then
                    lblErrorMessage.Text = ""
                    lblErrorMessage.Width = 1
                End If

                'ExpandOrContractSelectedShape()
            End If

            Session("sdsBatCalledFiles") = sdsBatCalledFiles
            Session("sdsFileCommentLines") = sdsFileCommentLines
            Session("sdsTextFiles") = sdsTextFiles
            Session("sdsTreeNodes") = sdsTreeNodes
            Session("sdsCommentsDictionary") = sdsCommentsDictionary
            Session("sdsUsers") = sdsUsers
            Session("sdsUserVSDFiles") = sdsUserVSDFiles
            Session("sdsUtilTreeNodes") = sdsUtilTreeNodes

        Catch ex As Exception
            ShowError(ex)
        End Try
    End Sub

    Protected Sub btnOpen_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnOpen.Click
        Try
            If ddlFilesList.SelectedItem.Text.EndsWith(" ***") Then
                'Get VSD & load
                GetVSDandXMLFiles(ddlFilesList.SelectedValue)
            Else
                CreateTree(ddlFilesList.SelectedValue)
            End If
        Catch ex As Exception
            ShowError(ex)
        End Try
    End Sub

    Protected Sub btnCreateVisio_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnCreateVisio.Click
        Try

            'pnlVisio.Visible = False
            CreateTree(ddlFilesList.SelectedValue)

            BuildFlowchart(tvwStructure.Nodes(0))

            'GetFileStatsFile()

            'ddlFilesList_SelectedIndexChanged(sender, e)
            'lblFileName.Text = ddlFilesList.SelectedValue

            tabsHIPO.ActiveTab = tabVisio
            'tabsHIPO_ActiveTabChanged(tabsHIPO, e)

        Catch ex As Exception
            ShowError(ex)
        End Try

    End Sub

    Protected Sub btnCreateTree_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnCreateTree.Click
        Try
            CreateTree(ddlFilesList.SelectedValue)
            'btnCreateVisio.Visible = True
            tabsHIPO.ActiveTab = tabTree
        Catch ex As Exception
            ShowError(ex)
        End Try
    End Sub

    Protected Sub tvwDisplay_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tvwStructure.SelectedNodeChanged
        'Show Node's comments in textbox
        Try
            txtComments.Text = tvwStructure.SelectedNode.ToolTip
            lblCommentFileName.Text = tvwStructure.SelectedNode.Text
        Catch ex As Exception
            ShowError(ex)
        End Try
    End Sub

    Protected Sub btnUpdateComment_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateComment.Click
        Try
            'tvwStructure.SelectedNode.ToolTip = txtComments.Text
            'Get the FileID
            Dim sFileID$ = ViewState("SelectedShapeFileID")
            If sFileID.Length = 0 Then Exit Sub

            'For each Comment Item
            For iLine As Integer = 0 To cblComments.Items.Count - 1
                'update its IsVisibleLine setting from the cblComments
                Dim oItem As ListItem = cblComments.Items(iLine)
                With sdsFileCommentLines.UpdateParameters
                    !FileID.DefaultValue = sFileID
                    !LineID.DefaultValue = iLine + 1
                    !IsVisibleLine.DefaultValue = oItem.Selected
                End With
                sdsFileCommentLines.Update()
            Next

            'Save the comment dictionary entry
            With sdsCommentsDictionary
                .DeleteParameters!FileID.DefaultValue = sFileID
                .Delete()

                .InsertParameters!FileID.DefaultValue = sFileID
                .InsertParameters!CommentLines.DefaultValue = txtComments.Text
                .Insert()
            End With

        Catch ex As Exception
            ShowError(ex)
        End Try
    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnSave.Click
        Try
            SaveVSD(ddlFilesList.SelectedValue)

        Catch ex As Exception
            ShowError(ex)
        End Try
    End Sub

    Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnPrint.Click
        Try
            'Open the drawing in Visio
            Dim App As Visio.Application = New Visio.InvisibleApp()
            Dim Doc As Visio.Document = App.Documents.Open(Server.MapPath(AppSettings("DefaultVSDFileName")).Replace(".vsd", UserName() & ".vsd"))

            'Print the drawing
            Doc.Print()

            'Close Visio
            App.Quit()
            App = Nothing

        Catch ex As Exception
            ShowError(ex)
        End Try
    End Sub

    Protected Sub btnRefresh_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnRefresh.Click
        Try
            ExpandOrContractSelectedShape()
        Catch ex As Exception
            ShowError(ex)
        End Try
    End Sub


    'Protected Sub ddlFilesList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlFilesList.SelectedIndexChanged
    '    Try
    '        'btnCreateVisio.Visible = False
    '        'If ddlFilesList.Items.Count Then
    '        '    Dim sFileName$ = ddlFilesList.SelectedItem.Text
    '        'End If
    '    Catch ex As Exception
    '        ShowError(ex)
    '    End Try
    'End Sub

    Protected Sub ddlVSDFilesList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlVSDFilesList.SelectedIndexChanged
        'Try
        '    GetVSDandXMLFiles()
        'Catch ex As Exception
        '    ShowError(ex)
        'End Try
    End Sub

    Protected Sub dgrdFilesList_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles dgrdFilesList.SortCommand
        Try
            SortFilesList(e)
        Catch ex As Exception
            ShowError(ex)
        End Try
    End Sub

    Protected Sub tvwStructure_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tvwStructure.SelectedNodeChanged
        Stop
    End Sub

    Private Sub GetVSDFilesList(ByRef ddl As DropDownList)
        Dim oDirInfo As DirectoryInfo = Computer.FileSystem.GetDirectoryInfo(Server.MapPath("VSD"))
        Dim sUserName$ = UserName()
        If oDirInfo.Exists Then
            For Each sFile As String In Directory.GetFiles(Server.MapPath("VSD"), String.Format("*{0}.vsd", sUserName))
                Dim sFileName$ = IO.Path.GetFileNameWithoutExtension(sFile).Split(".")(0)
                If sFileName <> IO.Path.GetFileNameWithoutExtension(ConfigurationManager.AppSettings("DefaultVSDFilename")) Then
                    ddl.Items.Add(New ListItem(sFileName$.ToUpper, sFile))
                End If
            Next
        End If
    End Sub

    Private Function UserName$()
        Dim saUserName$() = Request.LogonUserIdentity.Name.Split("\")
        Dim sUserName$ = ""
        If Not IsNothing(saUserName) AndAlso saUserName.Length Then
            sUserName = "." & saUserName(saUserName.Length - 1)
        End If
        Return sUserName
    End Function

    Private Sub GetBatchFilesList(ByRef ddl As DropDownList)
        Dim oDirInfo As DirectoryInfo = Computer.FileSystem.GetDirectoryInfo(ViewState("BatchPath"))
        If oDirInfo.Exists Then
            For Each sFile As String In Directory.GetFiles(ViewState("BatchPath"), "*.bat")
                Dim sFileName$ = IO.Path.GetFileNameWithoutExtension(sFile).ToUpper
                Dim oItem As ListItem = ddlVSDFilesList.Items.FindByText(sFileName)
                If not isnothing(oItem) Then
                    sFileName &= " ***"
                End If
                ddl.Items.Add(New ListItem(sFileName$, sFile))
            Next
        End If
    End Sub

    Private Sub GetSkippedFilesList(ByRef cbl As CheckBoxList)
        Dim saSkip$() = AppSettings("ByPass").Split(",")
        For Each s As String In saSkip
            cbl.Items.Add(s)
        Next
    End Sub

    Private Function GetFileStatsFile() As HIPO.aJobStatsFile
        Return Nothing
        Exit Function

        'Clear old sort indicators
        For Each oCol As DataGridColumn In dgrdFilesList.Columns
            'Remove sort-direction indicator from prev sorted column
            oCol.HeaderText = oCol.HeaderText.Replace(" ^", "").Replace(" v", "")
        Next

        Session("FileStatsSet") = Nothing
        Dim oFileStatsTable As New HIPO.aJobStatsFile()

        Try
            dgrdFilesList.DataSource = oFileStatsTable.FileStatsTable
            dgrdFilesList.DataBind()
        Catch
        End Try

        Return oFileStatsTable
    End Function

    Private Sub SortFilesList(ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs)

        Dim oFileStatsTable As New HIPO.aJobStatsFile(dgrdFilesList, e)

        'Show the sort results
        dgrdFilesList.DataSource = oFileStatsTable.FileStatsView
        dgrdFilesList.DataBind()

    End Sub

    Private Sub CreateTree(ByVal psBatchFilePathName$)
        Try
            'lblProgressMessage.Text = "Please wait, analysing files tree ..."
            If lblTreeName.Text = IO.Path.GetFileName(psBatchFilePathName) Then
                'Already have tree, just need to reset level
                Dim oPageSize As New HIPO.aPageSize(Me.txtDepth.Text, lblMaxDepth.Text)
                With oPageSize
                    .SetPageDepth(tvwStructure.Nodes(0))
                    lblPageWidth.Text = .PageSize.Width
                    lblPageHeight.Text = .PageSize.Height
                End With
            Else
                'Recursively adds nodes to the treeview
                'Session("HIPOTree") = New HIPO.aHIPOTree

                With sdsTreeNodes
                    .DeleteParameters!VSDFileID.DefaultValue = 0
                    .Delete()
                End With

                Dim oBat As New HIPO.aBatchTextFile(psBatchFilePathName)
                With oBat
                    .Depth = txtDepth.Text

                    txtBat.Text = .WholeText
                    lblBatchFileText.Text = .FilePathName
                    lblTreeName.Text = IO.Path.GetFileName(.FilePathName)

                    .CreateTree(psBatchFilePathName, tvwStructure, ViewState)

                    'lblMaxDepth.Text = .MaxDepth

                    lblPageWidth.Text = .DrawingPageSize.Width
                    lblPageHeight.Text = .DrawingPageSize.Height

                    'ajaxUpDownExtender.Maximum = lblMaxDepth.Text
                End With
            End If



        Catch exPathBad As System.ArgumentException
            Throw New Exception("Can't locate batch file or path selected.", exPathBad)
        End Try

    End Sub

    Private Sub ExpandOrContractSelectedShape()

        Dim sPostBackCtl$ = Page.Request.Params("__EVENTTARGET")

        If sPostBackCtl = "Viewer1" Then

            Dim iShapeID% = Val(Page.Request.Params("__EVENTARGUMENT"))

            'Can get the shape's file id from it's node
            'and load the comments editor - or only load it on demand

            'Would be nice if could start visio before affecting tree
            'so if Visio doesn't start, tree remains unchnaged

            ExpandContractNodes(tvwStructure.Nodes(0), iShapeID)

            If Not IsNothing(moNode) Then
                moNode.Target = IIf(moNode.Expanded.Value, "", "_top")

                ViewState("SelectedShapeFileID") = moNode.ImageToolTip

                lblShapeFile.Text = moNode.ImageToolTip
                If File.Exists(lblShapeFile.Text) Then
                    'If it's a batch file, could open it up in a new page, which will gen a new tab!!!
                    txtShapeFile.Text = File.ReadAllText(lblShapeFile.Text)
                End If

                GetShapeComments(moNode.ImageToolTip)

                If chkExpandable.Checked Then
                    Try
                        BuildFlowchart(tvwStructure.Nodes(0))
                    Catch ex As Exception
                        'Should catch Visio errors here 
                        'and try to restart it
                        'Stop
                    End Try

                End If
            End If
        End If

    End Sub

    Sub GetShapeComments(ByVal psFileID$)
        'Bind the shape's comments to the comments check list
        'to the sdsFileCommentLines dataview
        'filtered by the node's FileID
        sdsComments.SelectParameters!FileID.DefaultValue = psFileID
        Dim dv As DataView = sdsComments.Select(Empty)
        cblComments.DataBind()

        'Bind the checkboxes here
        For Each oItem As ListItem In cblComments.Items
            oItem.Selected = oItem.Value
        Next

        'Bind the Comments Dictionary textbox
        'to the Comments Dictionary dataview
        'filtered by userid and fileid
        sdsCommentsDictionary.SelectParameters!FileID.DefaultValue = psFileID
        'sdsCommentsDictionary.SelectParameters!FileID.DefaultValue = psFileID
        dv = sdsCommentsDictionary.Select(Empty)
        If dv.Table.Rows.Count Then
            txtComments.Text = dv.Table.Rows(0)!CommentLines
        End If
    End Sub

    Private Sub ExpandContractNodes(ByRef poNode As TreeNode, ByVal iShapeId%)


        For Each aNode As TreeNode In poNode.ChildNodes
            'How to limit to first child?
            Dim saValue$() = aNode.Value.Split(",")

            If saValue.Length > 1 AndAlso Val(saValue(1)) = iShapeId Then
                moNode = aNode
                With aNode
                    .Selected = True
                    If chkExpandable.Checked Then
                        .Expanded = Not (.Expanded.Value)
                        .Target = IIf(.Expanded.Value, "", "_top")
                        If .Expanded.Value Then
                            If chkExpandAll.Checked Then
                                .ExpandAll()
                            Else
                                'If we just expanded and it's not an Expand All
                                ' and if the first child is an input node
                                If .ChildNodes.Count > 0 AndAlso .ChildNodes(0).Checked = True Then
                                    ' expand it and collapse and _top its first child, the exe
                                    With .ChildNodes(0)
                                        .Expanded = True
                                        .Target = ""
                                        With .ChildNodes(0)
                                            .Expanded = False
                                            '.target = "_top"
                                        End With
                                    End With
                                End If

                                'If chkExpandAll.Checked = True Then
                                '    ExpandChildren(aNode)
                                'End If

                            End If
                        Else
                            'Do something for collapsing?
                            If chkExpandAll.Checked Then
                                .CollapseAll()
                            End If
                        End If
                    End If
                End With
                Exit For
            End If
            ExpandContractNodes(aNode, iShapeId)
        Next


    End Sub

    Private Sub ExpandChildren(ByRef poNode As TreeNode)
        'Expand All
        For Each aChildNode As TreeNode In poNode.ChildNodes
            aChildNode.Expanded = True
            ExpandChildren(aChildNode)
        Next
    End Sub


    Private Sub BuildFlowchart(ByRef poNode As TreeNode)
        Try

            'CType(UpdateProgress1.FindControl("lblProgressMessage"), Label).Text = "Please wait, drawing process map ..."
            Dim sFileName$ = poNode.Text.Replace(vbCrLf, "")
            'Create a new visio diagram
            Dim oVisioDiagram As New HIPO.aVisioTreeDrawing(poNode, sFileName)
            Using oVisioDiagram.VisioApp
                Try

                    Dim oPageSize As New HIPO.aPageSize(txtDepth.Text, lblMaxDepth.Text)

                    With oPageSize
                        .CalcPageHeight(poNode)
                        lblPageWidth.Text = .PageSize.Width
                        lblPageHeight.Text = .PageSize.Height
                    End With


                    oVisioDiagram.PageSize = oPageSize.PageSize

                    Dim sText$ = oVisioDiagram.BuildFlowchart(poNode, sFileName)

                    Session("ShapesNode") = oVisioDiagram.ShapesNode

                    lblPages.Text = sText & _
                     oVisioDiagram.nPageCount & " " & oVisioDiagram.sPageType & IIf(oVisioDiagram.nPageCount > 1, " pages", " page ")


                Catch exCOM As System.Runtime.InteropServices.COMException
                    Throw New System.Runtime.InteropServices.COMException("Couldn't access Visio.")

                Finally
                    oVisioDiagram = Nothing
                End Try
            End Using
        Catch
            Throw
        End Try


    End Sub


    Private Sub GetVSDandXMLFiles(ByVal psBATPathFileName$)
        'Copy the file to our viewer's page
        'This will update the drawing after the postback
        Dim sRootFileName$ = IO.Path.GetFileNameWithoutExtension(psBATPathFileName)
        Dim sUserName$ = UserName()
        Dim sFileName$ = Server.MapPath(String.Format("VSD\{0}{1}.vsd", sRootFileName, sUserName))
        Dim sDefaultFileName$ = Server.MapPath(AppSettings("DefaultVSDFileName")).Replace(".vsd", sUserName & ".vsd")
        File.Copy(sFileName, sDefaultFileName, True)

        ''Copy the xml file to the default
        'If File.Exists(sFileName.ToUpper.Replace("VSD", "XML")) Then
        '    File.Copy(sFileName.ToUpper.Replace("VSD", "XML"), sDefaultFileName.ToUpper.Replace("VSD", "XML"), True)

        '    'Bind the xml file to the files list
        '    Dim oFileStatsTable As HIPO.aJobStatsFile = GetFileStatsFile()
        '    dgrdFilesList.Caption = ddlVSDFilesList.SelectedValue
        '    lblPages.Text = oFileStatsTable.FileStampSize(sFileName)
        'End If

        'Get the batch file's text
        Dim sPathFileName$ = IO.Path.Combine(ViewState("BatchPath"), sRootFileName & ".bat")
        Dim oBatchFile As New HIPO.aTextFile(sPathFileName, True)
        txtBat.Text = oBatchFile.WholeText
        oBatchFile = Nothing

        'lblFileName.Text = ddlVSDFilesList.SelectedValue

        'Rebuild the treeview for this VSD File
        Dim sVSDFileName$ = IO.Path.GetFileNameWithoutExtension(sFileName)

        'Need to copy the VSDFile's TreeNodes to VSDFileID=0
        CopyTreeNodesToDefault(sVSDFileName)
        RebuildTreeview()

        GetCalledBatchFilesList(sVSDFileName)

    End Sub

    Private Sub CopyTreeNodesToDefault(ByVal psVSDFileName$)
        'Get the VSDFileID for this filename
        Dim sVSDFileID$ = GetVSDFileID(psVSDFileName)

        'Delete the old VSDFileID=0 records
        With sdsTreeNodes
            .DeleteParameters!VSDFileID.DefaultValue = 0
            .Delete()

            'Run the Update command on sdsTreenode, which will insert VSDFIleID recs into 0 records
            .UpdateParameters!VSDFileID.DefaultValue = sVSDFileID
            .UpdateParameters!NewVSDFileID.DefaultValue = 0
            .Update()
        End With
    End Sub

    Private Sub GetCalledBatchFilesList(ByVal psVSDFileName$)
        'look up BatFileID from the sdsUserVSDFile
        'filtered by VSDFileName

        'Bind the batchfiles gridview for this batch file
        'to the sdsBatCalledFiles dataview
        'filtered by BatFileID     
    End Sub

    Private Function GetVSDFileID$(ByVal psVSDFileName$)
        'Get the VSDFileID record using sFileName against UserVSDFiles table
        Dim dv As DataView
        With sdsUserVSDFiles
            With .SelectParameters
                !VSDFilename.DefaultValue = psVSDFileName
            End With
            dv = .Select(Empty)
            'If we dont find nn id, exit the sub
            If dv.Table.Rows.Count = 0 Then
                Return ""
                Exit Function
            End If
        End With
        Return dv.Table.Rows(0)!VSDFileID

    End Function

    Private Sub RebuildTreeview()
        'Clear the treeview
        tvwStructure.Nodes.Clear()

        'Get the Treenodes for the VSDFileID
        With sdsTreeNodes
            With .SelectParameters
                !VSDFileID.DefaultValue = 0 'dv.Table.Rows(0)!VSDFileID
            End With
            Dim dv As DataView
            dv = .Select(Empty)
            If IsNothing(dv) Then Exit Sub

            Dim collTreeNodes As New Collection
            'For each Treenode in TreeNodes
            For Each oRow As DataRow In dv.Table.Rows
                With oRow
                    'Build a treenode from the data
                    Dim oTreeNode As New TreeNode(!Text, !Value & "," & !ShapeId)
                    oTreeNode.ImageToolTip = IIf(!ImageToolTip Is DBNull.Value, "", !ImageToolTip)
                    oTreeNode.Expanded = !Expanded
                    oTreeNode.Checked = !Checked
                    oTreeNode.Target = IIf(!Target Is DBNull.Value, "", !Target)
                    oTreeNode.ToolTip = IIf(!ToolTip Is DBNull.Value, "", !ToolTip)

                    'Add the Treenode to a collection indexed by node id
                    collTreeNodes.Add(oTreeNode, !NodeId)

                    'If it's the root node then add directly to the treeview
                    If !ParentNodeId = 0 Then
                        oTreeNode.Expanded = True
                        tvwStructure.Nodes.Add(oTreeNode)
                    Else
                        'Lookup the node's parent in the collection, using it's parent node id
                        Dim oParentNode As TreeNode = collTreeNodes(!ParentNodeID)
                        'Add the node as its parent's childnode
                        oParentNode.ChildNodes.Add(oTreeNode)
                    End If
                End With
            Next

        End With

    End Sub


    Sub GetUserId()
        'Need to start or find a VSDFile record for this tree

        Dim sUserName$ = UserName.TrimStart(".")
        Session("UserName") = sUserName

        With sdsUsers
            With .SelectParameters
                !UserName.DefaultValue = sUserName
            End With
            Dim dv As DataView = .Select(New DataSourceSelectArguments)

            If dv.Table.Rows.Count = 0 Then
                'NEW USER
                With .InsertParameters
                    !UserName.DefaultValue = sUserName
                End With

                .Insert()

                dv = .Select(New DataSourceSelectArguments)
            End If

            Session("UserID") = dv.Table.Rows(0)!UserID

        End With

    End Sub


    Private Sub ShowError(ByVal ex As Exception)
        lblErrorMessage.Text = ex.Message
        If IsNothing(ex.InnerException) Then
            txtStacktrace.Text = ex.StackTrace
        Else
            txtStacktrace.Text = ex.InnerException.StackTrace
        End If
        txtStacktrace.Text = txtStacktrace.Text.Replace(Server.MapPath(""), "")
        Dim saLines$() = txtStacktrace.Text.Split(vbCrLf)
        txtStacktrace.Width = 0
        For Each sLine As String In saLines
            If txtStacktrace.Width.Value < sLine.Length * 4 Then
                txtStacktrace.Width = System.Web.UI.WebControls.Unit.Pixel(sLine.Length * 4)
            End If
        Next
        txtStacktrace.Height = 54 ' saLines.Length * 15 + 24
        lblErrorMessage.Width = txtStacktrace.Width.Value + 2
    End Sub

    Private Sub SaveVSD(ByVal psBATPathFileName$)
        'Get or create VSDFileID for current ddlBatFile and ass to UserVSDFiles table
        Dim sRootFileName$ = IO.Path.GetFileNameWithoutExtension(psBATPathFileName)
        Dim sUserName$ = UserName()
        Dim sFileName$ = Server.MapPath(String.Format("VSD\{0}{1}.vsd", sRootFileName, sUserName))
        Dim sVSDFileID$ = GetVSDFileID(IO.Path.GetFileNameWithoutExtension(sFileName))

        If sVSDFileID.Length Then
            'Copy the treenodes from Default 0 to sVSDFile
            'Delete the old VSDFileID records
            With sdsTreeNodes
                .DeleteParameters!VSDFileID.DefaultValue = sVSDFileID
                .Delete()

                'Run the Update command on sdsTreenode, which will insert VSDFIleID recs from 0 records
                .UpdateParameters!VSDFileID.DefaultValue = 0
                .UpdateParameters!NewVSDFileID.DefaultValue = sVSDFileID
                .Update()
            End With
        End If

        'Copy the default vsd file to the named vsd file
        Dim sDefaultFileName$ = Server.MapPath(AppSettings("DefaultVSDFileName")).Replace(".vsd", sUserName & ".vsd")
        File.Copy(sDefaultFileName, sFileName, True)

    End Sub



End Class



